<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Search Table Names and Fields</title>
    <script src="https://unpkg.com/axios@1.3.5/dist/axios.min.js"></script>
    <script src="https://unpkg.com/lodash@4.17.21/lodash.js"></script>
    <script src="https://unpkg.com/jquery@3.6.4/dist/jquery.js"></script>
    <script src="/layer-v3.5.1/layer/layer.js"></script>

    <style>
        table, th, td {
            border: 1px solid black;
            border-collapse: collapse;
            padding: 5px;
        }

        th {
            background-color: #ddd;
        }
        .tablenamecell{
         cursor: pointer;
            color: #1E9FFF;
        }
    </style>
</head>
<body>
<script id="resultTableTemplate" type="text/template">
    <% if (matchedTableNames.length > 0) { %>
    <table>
        <thead>
        <tr>
            <th >Table Name</th>
        </tr>
        </thead>
        <tbody>
        <% matchedTableNames.forEach(function(tableName) { %>
            <tr>
                <td class="tablenamecell"><%- tableName %></td>
            </tr>
        <% }); %>
        </tbody>
    </table>
    <% } else { %>
    <p>No Results Found.</p>
    <% } %>
</script>

<script id="resultTableFieldTemplate" type="text/template">
    <% if (matchedFields.length > 0) { %>
    <table>
        <thead>
        <tr>
            <th>Fields Name</th>
        </tr>
        </thead>
        <tbody>
        <% matchedFields.forEach(function(item) { %>
        <tr>
            <td ><%- item %></td>
        </tr>
        <% }); %>
        </tbody>
    </table>
    <% } else { %>
    <p>No Results Found.</p>
    <% } %>
</script>


<section>
    <label for="datasourceSelect">Data Source:</label>
    <select id="datasourceSelect"></select>
</section>

<h1>Search Table Names and Fields</h1>
<label for="searchString">Search String:</label>
<input type="text" id="searchString" />
<button id="searchButton">Search</button>
<br><br>
<div id="resultTable"></div>

<script>
    // 获取数据源列表
    async function getDatasourceList() {
        try {
            const response = await axios.get('/api/getDatabases').then(res=>res.data);
            const data = response.data;
            console.log("-> getDatasourceList data", data);
            const select = document.getElementById('datasourceSelect');
            // 添加选项到下拉框中
            data.forEach(function(datasource) {
                const option = document.createElement('option');
                option.text = datasource.database;
                option.value = datasource.id;
                select.add(option);
            });

            var dataSourceId=                 sessionStorage.getItem("dataSourceId")
            console.log("-> dataSourceId from session", dataSourceId);
            $('#datasourceSelect').change((e)=>{
                sessionStorage.setItem("dataSourceId",e.target.value)
            })

            $('#datasourceSelect').val(dataSourceId)
        } catch (error) {
            console.error(error);
        }
    }



    const searchButton = document.getElementById('searchButton');
    const resultTableTemplate = document.getElementById('resultTableTemplate').innerHTML;
    const resultTableRenderer = _.template(resultTableTemplate);

    const resultTableFieldTemplate = document.getElementById('resultTableFieldTemplate').innerHTML;
    const resultTableFieldRender = _.template(resultTableFieldTemplate);

    const textInput = document.getElementById('searchString');

    textInput.addEventListener('keyup', function(event) {
        if (event.keyCode === 13) { // Enter key
            searchButton.click(); // Trigger the button click event
        }
    });


    searchButton.addEventListener('click', async () => {
        const searchString = document.getElementById('searchString').value;
        const databaseId=document.getElementById('datasourceSelect').value
        console.log("-> databaseId", databaseId);
        try {
            const response = await axios.get(`/api/matchTableNameAndFeids?searchString=${searchString}&databaseId=${databaseId}`);
            const data = response.data;



            const resultTable = document.getElementById('resultTable');
            resultTable.innerHTML = `
           <div> ${resultTableRenderer(data)}</div>
           <br/>
            ${resultTableFieldRender(data)}
            `;


            //加入点击时间
            document.querySelectorAll('.tablenamecell').forEach(dom=>{
                dom.removeEventListener('click',clickTableName)
                dom.addEventListener('click',clickTableName)
            })
        } catch (error) {
            console.error(error);
        }
    });

    async function  clickTableName(e){
        var tableName=e.target.textContent.trim()
        console.log("-> tableName", tableName);
        const databaseId=document.getElementById('datasourceSelect').value
        console.log("-> databaseId", databaseId);
        var result=await axios.get(`/api/showddl?databaseId=${databaseId}&tableName=${tableName}`).then(res=>res.data)
        console.log("-> result", result);
        console.log("-> tableName", tableName);
        var ddl=result&&
            result.data&&
            result.data[0]&&
            result.data[0]['Create Table']
        console.log("-> ddl", ddl);

        layer.open({
            area: ['420px', '420px'], //宽高
            type: 1,
            title: result &&
                result.data &&
                result.data[0] &&
                result.data[0]['Table'],
            shade: false,
            content: `
           <div class="container">
                <div>
                  <button class='triggerclass'>复制为json</button>
                </div>
                <pre >${ddl}</pre>
            </div>
            `,
            success(){
                $('.triggerclass').click(async e=>{
                    var result=await axios.post('/api/getjsonfromddl',{
                        ddl
                    }).then(res=>res.data).then(res=>res.data)

                    if(result){
                        layer.open({
                            type: 1,
                            title: false,
                            closeBtn: 0,
                            shadeClose: true,
                            content: `
                            <pre style='max-width:666px;'>${JSON.stringify(result)}</pre>
                            `
                        });
                    }



                  // var ddl=  $(e.target).parents('.container')[0]).find('pre').text()
                })
            }
        });


    }


   function  init(){
       getDatasourceList()
   }

    init()
</script>
</body>
</html>